<?php

/*
 * 对外API接口
 */

/**
 * Description of IndexController
 *
 * @author yunbo
 */
namespace Api\Controller;
use Think\Controller;
use Qwadmin\Model;
class TaskrunController extends Controller{
    
   
    //初始化
    public function _initialize() {
        // 请求方式检测

    }
    
    /**
     * 对外请求接口
     */
    public function Index() {
        //验证商家是否存在
        echo "auto run task";

    }
    
	
	public function Autorun() {
        //验证商家是否存在
		error_reporting(0);
        echo "start auto run task.<br/>";
        $this->gettasklist(); ///更新需要运行的列表
		$this->runtask();
		file_put_contents("runlongtimes.log",$s,FILE_APPEND);
		
    }
	public function runtask()
	{
		
		$taskrun=M('taskrun')->where('runed=0 and runtime<'.time())->select();
		
	    //echo php_sapi_name();
		//die();
		echo "create client.<br/>";
		$client = new \swoole_client(SWOOLE_SOCK_TCP);
		var_dump($client);
		if(!$fp = $client->connect("127.0.0.1", 9501 , -1)) {
            echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
            return;
            }
		
		echo "task list:<br>";
		foreach($taskrun as $k =>$task)
		{
	        echo "process this task:<br><pre>";
			///var_dump($task);
			//swoole client 发送任务的方式
			echo "send a process<br>";
			$task['action']='autotask';  ///自动任务的处理标识
			$result=$client->send(json_encode($task));
			var_dump($result);
			echo "end a process<br>";
			//var_dump($client->recv());

			/*
			///常规模式
			$obj=new $task['model'];
			$rsp=$obj->$task['method']($task['args']);
			*/
		
			/*
			///cgi-cli模式支持
			echo "create thread for ".$task['hash']."<br/>";
			
			$taskthread[$k]=new \Qwadmin\Model\TaskthreadModel($task['hash']);
			echo "thread".$task['hash']." started;<br/>";
			$taskthread[$k].start();
			*/
			$task['runed']=1;
			$task['rsp']=$rsp;
			//M('taskrun')->save($task);
			
		}
		
		$client->close();
	}
	
	public function gettasklist()
	{
		////获取可重复运行的任务列表
		/// 最小更新到当前小时内
		$year=date("Y");
		$month=date("m");
		$days=date('d');
		$hours=date('H');
		$mins=date('i');

		/*
		   比如是：0.5 表示 /5 如果是月的话是每5月执行一次，但是只会执行每年0,5,10月运行  0.1是每年执行一次
		*/
		
		$where="(year=".$year." or year<1) and (month=".$month." or month<1) and (days=".$days." or days<1) and (hours=".$hours." or hours<1) ";
        
		$tasklist=M('tasklist')->where($where)->select();
		
		//var_dump($tasklist);
		foreach($tasklist as $k =>$task)
		{
		
		    $cyear=$this->getcnum($year,$task['year']);
		    $cmonth=$this->getcnum($month,$task['month']);
		    $cdays=$this->getcnum($days,$task['days']);
		    $chours=$this->getcnum($hours,$task['hours']);
		    $cmins=$this->getcnum($mins,$task['mins']);
		     
		
			$task['runtime']=strtotime("$cyear-$cmonth-$cdays $chours:$cmins:00");
			///bug list: 如生成：2016-12-13 10:60:00这种时间，strtotime不能使用
			echo "$cyear-$cmonth-$cdays $chours:$cmins:00<br/>";
			//echo 'next runtime:'.$task['runtime']."<br/>";
            $task['runtime'] =mktime($chours, $cmins, 1, $cmonth, $cdays, $cyear);
			$task['hash']=md5('task-'.$task['runtime']."-".$task['id']);
			unset($task['year']);
			unset($task['month']);
			unset($task['days']);
			unset($task['hours']);
			unset($task['mins']);
			unset($task['id']);
			$taskrun=M('taskrun')->where("hash='".$task['hash']."'")->find();
			if(!$taskrun)
			{
				M('taskrun')->add($task);
			}
			
			
		}
		 
		
	}
	
	public function getcnum($num1,$num2)
	{
		///根据$num1,$num2进行取数，
		///$num1 为一个数
		///$num2 可为0,0.x,xx 
		///如 $num2=0.5 表示如果$num1 如果被5整除，则返回$num1,如果有余数，则获取下一个被5整除的数。		
		//echo "nums:".$num1." ---".$num2."<br/>";
		if($num2<1&&$num2>0)
		{
			
		    $divnum=end(explode('.',$num2));
			return $num1+($divnum-($num1%$divnum==0?$divnum:$num1%$divnum));
		}elseif($num2==0)
		{
			return $num1;
		}else{
			return $num2;
		}	
		
	}
    
}
